import logging
from typing import AnyStr

import jpype

from configs import dify_config

jvmpath = dify_config.JVM_PATH

logger = logging.getLogger(__name__)


def __import__():
    init()


def init():
    # jvmpath =jpype.getDefaultJVMPath()
    # 启动 Java 虚拟机，并指定 JAR 文件路径
    try:
        jpype.startJVM(jvmpath=jvmpath)
    except Exception as e:
        logger.info(f"jvm start failed!, exception: {str(e)}")


def __del__():
    jpype.shutdownJVM()


def loadJar(jarPath: str):
    # mypath = "-Djava.class.path=" + jarPath
    if not jpype.isJVMStarted():
        init()
    jpype.addClassPath(jarPath)


def getClass(clsName: str):
    jarClass = jpype.JClass(clsName)
    return jarClass


def loadByte(byte: AnyStr):
    return jpype.JArray(jpype.JByte)(byte)

